package com.zr.bookcorner.activity;

import android.os.CountDownTimer;
import android.text.Html;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zh.baselibrary.base.BaseActivity;
import com.zh.baselibrary.base.BaseNoIMActivity;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.utils.ClickUtils;
import com.zh.baselibrary.utils.IntentUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.manager.BookInfo;
import com.zr.andealib.util.HardEvent;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.andealib.util.model.InventoryReport;
import com.zr.bookcorner.BookApplication;
import com.zr.bookcorner.R;
import com.zr.bookcorner.adapter.BookManagerAdapter;
import com.zr.bookcorner.constant.Constant;
import com.zr.bookcorner.dialog.BorrowSubmitDialog;
import com.zr.bookcorner.dialog.ManagerSubmitDialog;
import com.zr.bookcorner.presenter.BorrowReturnDetailPresenter;
import com.zr.bookcorner.presenter.ManagerDetailPresenter;
import com.zr.bookcorner.presenter.view.OperateDetailView;
import com.zr.bookcorner.service.VoiceEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ManagerDetailActivity extends BaseNoIMActivity<ManagerDetailPresenter> implements OperateDetailView {
    @BindView(R.id.rv_book)
    RecyclerView mRvBook;
    @BindView(R.id.tv_error)
    TextView mTvError;
    @BindView(R.id.ll_error)
    LinearLayout layout;
    @BindView(R.id.pb)
    ProgressBar mPb;

    /**
     * 空闲时间
     */
    private static final Long MILLISINFUTURE = (long) 60 * 1000;
    /**
     * 倒计时间隔
     */
    private static final Long COUNTDOWNINTERVAL = (long) 1 * 1000;
    int boxNum;
    BookManagerAdapter mAdapter;
    CountDownTimer countTimer;


    @Override
    protected int getLayoutId() {
        return R.layout.manager_detail_activity;
    }

    @Override
    protected void init() {
        boxNum = getIntent().getIntExtra(ExtraName.KEY_DATA, -1);
        mAdapter = new BookManagerAdapter(new ArrayList<>());
        mRvBook.setLayoutManager(new GridLayoutManager(this, BookApplication.isBig() ? 5 : 3));
        mRvBook.setAdapter(mAdapter);
        countTimer = new CountDownTimer(MILLISINFUTURE, COUNTDOWNINTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                mPresenter.setDoorClosed(true);
                mPresenter.toSubmit();
            }
        };
    }

    @Override
    protected ManagerDetailPresenter createPresenter() {
        return new ManagerDetailPresenter();
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void Event(HardEvent hardEvent) {
        int flag = hardEvent.getFlag();
        if (flag == AndeaConstant.CALL_READ_CHECK_SUCCSES) {
            List<InventoryReport> listTags = (List<InventoryReport>) hardEvent.getData();
            mPresenter.doCheck(listTags);
        } else if (flag == AndeaConstant.CALL_LOCK_STATUS_SUCCSES) {
            mPresenter.openError(2);
        }
    }

    @OnClick({R.id.tv_submit, R.id.iTvTitleLeft})
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) {
            if (v.getId() == R.id.tv_submit) {
                if (mPresenter.isDoorOpen()) {
                    ToastView.showLong("请先关闭柜门，再进行提交");
                } else {
                    showDialog();
                }
            } else {
                if (mPresenter.isDoorOpen()) {
                    ToastView.showLong("请先关闭柜门，再进行返回");
                } else {
                    showDialog();
                }

            }
        }
    }

    private void showDialog() {
        countTimer.cancel();
        if (TextUtils.isEmpty(mPresenter.getAllTip().trim())) {
            ToastView.showShort("当前未进行上下架操作");
            finish();
        } else {
            LogUtils.e(mPresenter.getAllTip());

            if (TextUtils.isEmpty(mPresenter.getErrorTip())) {
               // TTSUtils.getInstance().speak(getString(R.string.to_submit));
                EventBus.getDefault().post(new VoiceEvent(getString(R.string.to_submit)));
            }
            else {
               // TTSUtils.getInstance().speak(getString(R.string.have_error));
                EventBus.getDefault().post(new VoiceEvent(getString(R.string.have_error)));
            }

            ManagerSubmitDialog.DialogListener listener = new ManagerSubmitDialog.DialogListener()
            {
                ManagerDetailPresenter bp;
                @Override
                public void setPresenter(ManagerDetailPresenter bp) {
                    this.bp = bp;
                }

                @Override
                public void submit() {
                    if(bp!=null)
                    bp.toSubmit();
                }

                @Override
                public void mistakes() {
                    if(bp!=null) {
                        countTimer.start();
                        bp.openDoor();
                    }
                }
            };
            listener.setPresenter(mPresenter);

            ManagerSubmitDialog mSubmitDialog = new ManagerSubmitDialog(this, R.style.DialogTheme,listener);

            mSubmitDialog.show();
            //设置提示信息
            mSubmitDialog.setMessageInfo(mPresenter.getName(Constant.UP), mPresenter.getName(Constant.DOWN), mPresenter.getName(Constant.RETURN), mPresenter.getErrorTip(), mPresenter.getErrorSize());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            countTimer.start();
        } else {
            countTimer.cancel();
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        countTimer.start();
        mPresenter.initDevice(boxNum);

    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
        mPresenter.onDestroy();
        if (countTimer != null)
            countTimer.cancel();
    }

    @Override
    public void onSuccess(Object object) {
        IntentUtils.instance().startActivityFinish(this, HomeActivity.class);
    }

    @Override
    public void onHint(String hint) {
        ToastView.showShort(hint);
        //  finish();
    }

    @Override
    public void getDataSuccess(List<BookInfo> data) {
        if (mPb.getVisibility() == View.VISIBLE) {
            mPb.setVisibility(View.GONE);
        }
        mAdapter.clearAdd(data);
        countTimer.cancel();
        countTimer.start();
        mTvError.setText(Html.fromHtml(mPresenter.getAllTip()));
        if (TextUtils.isEmpty(mPresenter.getAllTip()))
            layout.setVisibility(View.GONE);
        else
            layout.setVisibility(View.VISIBLE);
    }

    @Override
    public void loading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mPb.getVisibility() == View.GONE) {
                    mPb.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void doorClose() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDialog();
            }
        });
    }

}
